package com.molin.threadTest.threadSecurety.funccode;

public class TicketRunnable implements Runnable {
    private int ticketCount = 100;

    @Override
    public void run() {
        while (true) {
            //售票窗口2使用同步代码块方式运行
            if("售票窗口2".equals(Thread.currentThread().getName())){
                //同步代码块和同步方法共用一个锁
                synchronized (this){
                    if (ticketCount == 0) {
                        return;
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticketCount--;
                    System.out.println(Thread.currentThread().getName() + "在售票，还剩下" + ticketCount + "张票");
                }
           }else {
                //使用同步方法运行
                if (sale() == false) {
                    return;
                }
            }
        }
    }

    private synchronized boolean sale() {
        if (ticketCount == 0) {
            return false;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ticketCount--;
        System.out.println(Thread.currentThread().getName() + "在售票，还剩下" + ticketCount + "张票");
        return true;
    }

}
